<template>
	<view>
		<customHeader :centerTitle="getTitle" backThem="light">
			<template v-slot:bg>
				<image class="head-bg" v-if="!searchPro" :src="require('@/managePackage/image/search_bg.png')"></image>
				<image class="head-bg" v-else :src="require('@/managePackage/image/primise.png')"></image>
			</template>
		</customHeader>
		<view class="bg-box">
			<view class="search-rows">
				<view>
					<view>
						<image :src="require('@/static/image/version/search.png')"></image>
						<input placeholder="海鲜" v-model="searchForm.keywords" @input="lisIpt"/>
					</view>
					<view class="btns" @click="search" v-if="!searchPro">搜索</view>
					<view v-else class="shop-cars" hover-class="hover_class" @click="goCar">
						<image :src="require('@/managePackage/image/shop_car.png')"></image>
						<text>购物车</text>
					</view>
				</view>
			</view>
			<view class="history-box" v-if="!searchPro">
				<view class="head">
					<text>搜索历史</text>
					<image v-if="historyData.length" :src="require('@/managePackage/image/del.png')" @click="delHis"></image>
				</view>
				<view class="his-type">
					<view v-for="(it, ix) in historyData" @click="checkType(it)" :key="ix">{{ it }}</view>
				</view>
			</view>
			<view class="search-filed trans" v-if="searchPro">
				<view v-for="(it, ix) in searchFiled" :key="ix"
				 @click="checkOrder(it)"
				 :class="{'activ': searchForm.orderby_field === it.id}">{{it.name}}
					<view v-if="it.id === 'shop_price'">
						<u-icon name="arrow-up-fill" :color="getSort.asc ? '#16f5b9': '#969696'" size="7"></u-icon>
						<u-icon name="arrow-down-fill" :color="getSort.desc ? '#16f5b9': '#969696'" size="7"></u-icon>
					</view>
				</view>
			</view>
			<view v-if="searchPro" class="set-htig">
				<view class="pro-list trans" v-if="shopList.length !== 0 && !proLoading">
					<scroll-view scroll-y="true" class="scoll-view"
					@scrolltolower="getMore"
					:throttle="false"
					>
						<view class="list-items" v-for="(it, ix) in shopList" :key="ix" @click="goDetail(it)" hover-class="hover_class">
							<image mode="aspectFill" :src="it.image"></image>
							<view>
								<view :class="{'clear-text': it.isTodaySeckill != 2}">
									<view v-if="it.isTodaySeckill == 2">秒杀</view>
									<text>{{ it.name }}</text>
								</view>
								<view class="des">{{it.describe}}</view>
								<view class="prices">
									<view>
										<text>￥</text>
										<view>{{it.shopPrice || 0}}</view>
									</view>
									<view @click.stop="addCart(it)" hover-class="hover_class">
										<view v-if="it.cartNum" class="add-car">
											<image :src="require('@/static/image/version/add.png')"></image>
											<view>{{it.cartNum}}</view>
										</view>
										<image v-else :src="require('@/static/image/version/car.png')"></image>
									</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
				<view v-if="proLoading" class="pro-list skills">
					<view class="load-emp" v-for="(it) in 6" :key="it">
						<u-skeleton
							rows="3"
							avatar
							:title="false"
						></u-skeleton>
					</view>
				</view>
				<view v-if="shopList.length === 0 && !proLoading" class="pro-list emptyds">
					<empty title="暂无商品信息"/>
				</view>
			</view>
		</view>
		<dialogPop cancelTxt="取消" @save="clearHis" okText="清空" ref="tipsPop" content="是否清空历史搜索记录？" />
		<rulePop ref="rulePop" @update="getCart" />
	</view>
</template>

<script>
import {
	productList,
	cartList
} from '@/utils/api/home.js'
import rulePop from '@/pages/home/component/rulePop'
export default {
	components: {
		rulePop
	},
	data() {
		return {
			searchPro: false,
			searchForm: {
				page: 1,
				keywords: '',
				orderby_field: '',
				orderby_type: ''
			},
			shopList: [],
			searchFiled: [
				{ name: '销量', id: 'sales_num' },
				{ name: '折扣', id: 'discount' },
				{ name: '价格', id: 'shop_price' },
			],
			historyData: [],
			proLoading: true,
			total: 0,
			cartData: []
		}
	},
	computed: {
		getTitle() {
			return this.searchPro ? '搜索结果' : '搜索'
		},
		getSort() {
			let type = this.searchForm.orderby_type
			return {
				asc: type === 'ASC',
				desc: type === 'DESC',
			}
		}
	},
	onLoad(data) {
		this.searchForm.keywords = data.val || ''
		this.search()
		let hisData = uni.getStorageSync('searchHistory')
		this.historyData = hisData ? JSON.parse(hisData) : [],
		this.getCart()
	},
	methods: {
		// 添加购物车
		addCart(item) {
			this.$refs.rulePop.openPop(item)
		},
		// 设置购物数量
		setCartNum() {
			let cartInfo = {} 
			this.cartData.forEach((it) => {
				if(cartInfo[it.product_id]) {
					cartInfo[it.product_id] += 1
				} else {
					cartInfo[it.product_id] = 1
				}
			})
			this.shopList.forEach((it) => {
				if(cartInfo[it.id]) {
					it.cartNum = cartInfo[it.id]
				}
			})
		},
		// 购物车列表
		getCart() {
			cartList().then((res) => {
				this.cartData = res.data || []
				this.setCartNum()
			})
		},
		getMore() {
			if(this.shopList.length >= this.total) {
				return
			}
			this.searchForm.page ++ 
			this.getProduct('load')
		},
		goDetail(item) {
			uni.navigateTo({
				url: '/managePackage/pages/shopDetail/index?id=' +item.id
			})
		},
		// 排序
		checkOrder(it) {
			this.searchForm.orderby_field = it.id
			if(it.id === 'shop_price') {
				let sorts = ''
				let type = this.searchForm.orderby_type
				if(!type) {
					sorts = 'ASC'
				} else if(type === 'ASC') {
					sorts = 'DESC'
				}
				this.searchForm.orderby_type = sorts
			} else {
				this.searchForm.orderby_type = ''
			}
			this.searchForm.page = 1
			this.getProduct()
		},
		// 获取商品
		getProduct(key) {
			if(!key) {
				this.proLoading = true
			} else {
				uni.showLoading({
					title: '加载中'
				})
			}
			productList(this.searchForm).then((res) => {
				this.total = res.data.total
				if(this.searchForm.page === 1) {
					this.shopList = res.data.list || []
				} else {
					this.shopList = this.shopList.concat(res.data.list)
				}
				this.setCartNum()
			}).finally(() => {
				uni.hideLoading()
				setTimeout(() => {
					this.proLoading = false
				}, 200)
			}).catch(() => {
				this.proLoading = false
			})
		},
		checkType(it) {
			this.searchForm.keywords = it
		},
		delHis() {
			this.$refs.tipsPop.open()
		},
		// 搜索
		search() {
			this.searchPro = true
			this.getProduct()
			let history = uni.getStorageSync('searchHistory')
			if(!this.searchForm.keywords) return
			if(history) {
				history = JSON.parse(history)
				history.push(this.searchForm.keywords)
			} else {
				history = [this.searchForm.keywords]
			}
			history = this.resetList(history)
			uni.setStorageSync('searchHistory', JSON.stringify(history))
			this.historyData = history
		},
		// 去重
		resetList(arr) {
		   let temp = []
		   arr.forEach((item, index) => {
			   arr.indexOf(item) == index ? temp.push(item) : null
		   })
		   return temp
	    },
		// 清空历史
		clearHis() {
			this.historyData = []
			uni.removeStorageSync('searchHistory')
		},
		lisIpt() {
			if(!this.searchForm.keywords) {
				this.searchPro = false
			}
		},
		// 购物车
		goCar() {
			uni.switchTab({
				url: '/pages/shopCar/index'
			})
		}
	}
}
</script>

<style scoped lang="scss">
@import './index.scss';
</style>